package server

import (
    "github.com/gogf/gf/frame/g"
    "github.com/gogf/gf/net/gtcp"
    "github.com/gogf/gf/os/glog"
)

var client *gtcp.Conn

func Run() {
    httpAddr := g.Config().GetString("server.http_ip") + ":" + g.Config().GetString("server.http_port")
    tcpAddr := g.Config().GetString("server.tcp_ip") + ":" + g.Config().GetString("server.tcp_port")
    http := gtcp.NewServer(httpAddr, handleHttp)
    tcp := gtcp.NewServer(tcpAddr, handleTcp)
    go http.Run()
    go tcp.Run()
    glog.Info("http run at " + httpAddr)
    glog.Info("tcp run at " + tcpAddr)
    glog.Info("server run")
    g.Wait()
}

func handleHttp(conn *gtcp.Conn) {
    defer conn.Close()
    data, err := conn.Recv(-1)
    glog.Info("http accept")
    if err == nil && client != nil {
        _, err = client.Write(data)
        glog.Info("send to tcp")
        if err == nil {
            res, err := client.Recv(-1)
            glog.Info("tcp accept")
            if err == nil {
                _, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\n"))
                _, _ = conn.Write([]byte("Content-Type: text/html;charset=utf-8\r\n"))
                _, _ = conn.Write([]byte("\r\n"))
                _, _ = conn.Write(res)
                glog.Info("send to http")
            }
        }
    } else {
        _, _ = conn.Write([]byte("HTTP/1.1 404 Bad Request"))
    }
}

func handleTcp(conn *gtcp.Conn) {
    client = conn
    select {}
}
